﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketClientZS7000
{
    public class ORMSocketClientHelp
    {
        private  string _ip=string.Empty;
        private int _port=0;
        private Socket _socket;
        private byte[] _buffer=new byte[1024*1024*2];
        private int _revDataLength = 0;
        public ORMSocketClientHelp(string ip,int port)
        {
            this._ip = ip;
            this._port = port;
        }
        public void ORMConnect(string targetIp,int targetPort)
        {
            try
            {
                _socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                _socket.Bind(new IPEndPoint(IPAddress.Parse(_ip),_port));
                _socket.Connect(new IPEndPoint(IPAddress.Parse(targetIp),targetPort));
                Console.WriteLine("连接成功");
            }
            catch (Exception)
            {

                throw;
            }
        }
        public void SendMessage(string strMes)
        {
            byte[] senddata=Encoding.ASCII.GetBytes(strMes);
            _socket.BeginSend(senddata,0,senddata.Length,SocketFlags.None,new AsyncCallback(ar => {
                Socket client =(Socket)ar.AsyncState;
                int byteSent = client.EndSend(ar);
            }),_socket);
        }
        public string ReciveMessage()
        {          
            // 异步接收数据示例
            _socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None,
                new AsyncCallback(ar => {
                    Socket client = (Socket)ar.AsyncState;
                    int bytesRead = client.EndReceive(ar);
                   // Console.WriteLine(Encoding.ASCII.GetString(_buffer).TrimEnd('\0'));
                }), _socket);
            Thread.Sleep(200);
            string str = Encoding.ASCII.GetString(_buffer).TrimEnd('\0');
            try
            {               
                double d = (double)int.Parse(str) / 1000;
                return d.ToString();
            }
            catch 
            {
                return "ER";
            }
          

        }
        public void ORMDisconnect()
        {
            try
            {
                _socket.Disconnect(true);
                _socket.Close();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
